package Day020_NIO_AIO.demo2_NIO2_AIO.Test4_AIO异步请求连接;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;

/**
 * @author zhangyan
 * @date 2020/5/13 14:06
 */
//没有意义

public class Server {
    public static void main(String[] args) throws Exception{

        //1. 获取服务器通道对象
        AsynchronousServerSocketChannel assc = AsynchronousServerSocketChannel.open();

        //2. 对象调用bind()方法 绑定团口号
        assc.bind(new InetSocketAddress(666));

        System.out.println(1);
        //3. accept()异步的方法,等待接收请求
        //匿名内部类
        assc.accept(null, new CompletionHandler<AsynchronousSocketChannel, Object>() {
            @Override
            public void completed(AsynchronousSocketChannel result, Object attachment) {
                //客户端连接成功后执行 completed()方法  回调函数
                //第一个参数客户端连接成功后返回的客户端通道对象
                //第二个参数:附件 没用
                System.out.println(3);

                //读数据
                //创建缓冲数组
                ByteBuffer b = ByteBuffer.allocate(1024);
                //异步 读数据: 使用无返回值的read()方法
                result.read(b, null, new CompletionHandler<Integer, Object>() {
                    @Override
                    public void completed(Integer result, Object attachment) {
                        //读取成功执行 completed()方法  回调函数
                        System.out.println(4);

                        //打印数据
                        System.out.println(new String(b.array(),0,result));
                    }

                    @Override
                    public void failed(Throwable exc, Object attachment) {
                        //读取失败后执行
                    }
                });
                System.out.println(5);
            }

            @Override
            public void failed(Throwable exc, Object attachment) {
                //连接失败后执行
            }
        });
        System.out.println(2);
        while (true){}


        /*

        //以前NIO
        ServerSocketChannel ssc = ServerSocketChannel.open();
        ssc.bind(new InetSocketAddress(666));
        //以前是直接返回客户端通道
        SocketChannel sc = ssc.accept();
        //读数据
        //创建ByteBuffer缓冲数组
        ByteBuffer b = ByteBuffer.allocate(1024);
        int len = asc.read(b);

        */
    }
}
